﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Mimoza.ObjectLayer;
using Mimoza.Apps.Console.ViewModel;

namespace Mimoza.Apps.Console.Commands
{
    class NewUpdateCommand : BaseConsoleCommand
    {
        UpdateViewModel m_viewModel = null;
        public NewUpdateCommand(UpdateViewModel viewModel)
        {
            m_viewModel = viewModel;
            m_viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(this.viewModel_PropertyChanged);
        }

        void viewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (m_viewModel.Visible)
            {
                this.Visible = true;
                this.Enabled = true;
            }
            else 
            {
                this.Visible = false;
                this.Enabled = false;
            }
        }

        public override void Execute()
        {
            Container cont = m_viewModel.Context as Container;

            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Title = "Select update file";
                dlg.Filter = "Update File (*.svu)|*.svu";
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Update newUpd = m_viewModel.Application.ObjectLayer.UpdateRepository.CreateUpdate();

                    using (FileStream stream = File.OpenRead(dlg.FileName))
                    {
                        newUpd.UpdateFileBody = stream;

                        m_viewModel.Application.ObjectLayer.UpdateRepository.Add(newUpd);
                    }
                }
            }
            catch (Exception e)
            {
                string error = "Command: NewUpdateCommand error - '" + e.ToString() + "'.";
                MessageBox.Show(null, error, "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                Mimoza.Common.Logger.Log.Error(error);
            }

        }
    }
}
